package fyzdb

import (
	"gitee.com/zibianqu/fyzdb/connection"
	"gitee.com/zibianqu/fyzdb/connection/mysql"
)

func DefaultDriver() string {
	return "mysql"
}

type BuilderObj struct {
	driverName string
}

// 设置驱动
func Driver(driver string) *BuilderObj {
	b := BuilderObj{
		driverName: driver,
	}
	return &b
}

// 会话
func Seesion(sessionIds ...int64) *mysql.SessionModel {
	session := mysql.Session(sessionIds...)
	return session
}

// 会话连接
func SC(p ...any) connection.IBuilder {
	sessionId := int64(0)
	connection := "default"
	for _, v := range p {
		if sid, ok := v.(int64); ok {
			sessionId = sid
		}
		if con, ok := v.(string); ok {
			connection = con
		}
	}
	session := mysql.Session(sessionId).SetConnection(connection)
	return session.Builder
}

// 设置连接信息
func Connection(connection string) connection.IBuilder {
	b := BuilderObj{
		driverName: DefaultDriver(),
	}
	builder := b.Connection(connection)
	return builder
}

func Table(table ...string) connection.IBuilder {
	b := BuilderObj{
		driverName: DefaultDriver(),
	}
	builder := b.Table(table...)
	return builder
}

func FetchAll(sql string, bindParam ...any) any {
	b := BuilderObj{
		driverName: DefaultDriver(),
	}
	return b.FetchAll(sql, bindParam...)
}

func FetchOne(sql string, bindParam ...any) map[string]any {
	b := BuilderObj{
		driverName: DefaultDriver(),
	}
	return b.FetchOne(sql, bindParam...)
}

func Execute(sql string, bindParam ...any) int64 {
	b := BuilderObj{
		driverName: DefaultDriver(),
	}
	return b.Execute(sql, bindParam...)
}

func Builder() *BuilderObj {
	b := BuilderObj{
		driverName: DefaultDriver(),
	}
	return &b
}

func (b *BuilderObj) Driver(driver string) *BuilderObj {
	b.driverName = driver
	return b
}

func (b *BuilderObj) Table(table ...string) connection.IBuilder {
	if b.driverName == DefaultDriver() {
		return mysql.Table(table...)
	}
	return nil
}

func (b *BuilderObj) Connection(connection string) connection.IBuilder {
	if b.driverName == DefaultDriver() {
		return mysql.Connection(connection)
	}
	return nil
}

func (b *BuilderObj) FetchAll(sql string, bindParam ...any) any {
	if b.driverName == DefaultDriver() {
		return mysql.Table("").FetchAll(sql, bindParam...)
	}
	return nil
}

func (b *BuilderObj) FetchOne(sql string, bindParam ...any) map[string]any {
	if b.driverName == DefaultDriver() {
		return mysql.Table("").FetchOne(sql, bindParam...)
	}
	return nil
}

func (b *BuilderObj) Execute(sql string, bindParam ...any) int64 {
	if b.driverName == DefaultDriver() {
		return mysql.Table("").Execute(sql, bindParam...)
	}
	return 0
}
